import React, { useEffect, useState } from 'react';
import { Table, Button, Card, Space, message, Upload, Modal, Input } from 'antd';
import { DownloadOutlined, UploadOutlined, StepForwardOutlined, RedoOutlined } from '@ant-design/icons';
import axios from 'axios';

const STEP_MAP = {
  0: '信息录入',
  1: '结果核对',
  2: '任务一帮助',
  3: '任务二帮助',
  4: '任务二结果核对',
};
const PASSWORD = '010101';

export default function ResultPage() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [stepLabel, setStepLabel] = useState('');
  const [authorized, setAuthorized] = useState(false);
  const [pwd, setPwd] = useState('');
  const [pwdModal, setPwdModal] = useState(true); // 控制弹窗显隐

  const checkPassword = () => {
    if (pwd.trim() === PASSWORD) {
      setAuthorized(true);
      setPwdModal(false);
      fetchData();
      fetchStep();
    } else {
      message.error('密码错误，请重试');
      setPwd('');
    }
  };

  /* 授权后再拉数据 
  useEffect(() => {
    if (!authorized) return;
    fetchData();
    fetchStep();
  }, [authorized]);*/

  const fetchData = async () => {
    try {
      const res = await axios.get('/api/students');
      setData(res.data);
    } catch {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchStep = async () => {
    try {
      const { data } = await axios.get('/api/option/step');
      setStepLabel(STEP_MAP[data.opvalue] || '');
    } catch {
      message.error('获取环节失败');
    }
  };

  const uploadProps = {
    name: 'file',
    action: '/api/resultsUpload',
    accept: '.xlsx,.xls',
    showUploadList: false,
    onChange(info) {
      const { status, response } = info.file;
      if (status === 'done') {
        setData(response);
        message.success('导入成功');
      } else if (status === 'error') {
        message.error('导入失败');
      }
    },
  };

  const nextStep = async () => {
    try {
      const { data } = await axios.post('/api/option/incr', { opkey: 'step' });
      setStepLabel(STEP_MAP[data.opvalue] || '');
    } catch {
      message.error('操作失败');
    }
  };

  const resetClass = async () => {
    try {
      const { data } = await axios.post('/api/option/zero', { opkey: 'step' });
      setStepLabel(STEP_MAP[data.opvalue] || '');
    } catch {
      message.error('操作失败');
    }
  };

  const columns = [
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '性别', dataIndex: 'gender', key: 'gender' },
    { title: '身高 (cm)', dataIndex: 'height', key: 'height' },
    { title: '体重 (kg)', dataIndex: 'weight', key: 'weight' },
    { title: '爱好', dataIndex: 'hobby', key: 'hobby' },
  ];

  /* 未授权时只渲染弹窗 */
  if (!authorized) {
    return (
      <Modal
        title="请输入访问密码"
        open={pwdModal}
        closable={false}
        maskClosable={false}
        okText="确认"
        cancelButtonProps={{ style: { display: 'none' } }}
        onOk={checkPassword}
      >
        <Input.Password
          value={pwd}
          onChange={(e) => setPwd(e.target.value)}
          placeholder="6 位数字密码"
          maxLength={6}
          onPressEnter={checkPassword}
        />
      </Modal>
    );
  }

  return (
    <div style={{ margin: 24 }}>
      <Card
        title="学生信息列表"
        extra={
          <Space>
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>导入预测结果</Button>
            </Upload>
            <Button icon={<StepForwardOutlined />} onClick={nextStep}>
              下一个环节
            </Button>
            <span style={{ marginLeft: 8, color: '#666' }}>当前环节：{stepLabel}</span>
            <Button icon={<RedoOutlined />} onClick={resetClass}>
              重置课堂
            </Button>
            <Button type="primary" icon={<DownloadOutlined />} href="/api/download" target="_blank">
              下载 Excel
            </Button>
          </Space>
        }
      >
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data}
          loading={loading}
          pagination={{ pageSize: 50, showSizeChanger: false }}
        />
      </Card>
    </div>
  );
}